package com.ruoyi.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.base.domain.*;
import com.ruoyi.base.domain.vo.BaseBsProjectVo;
import com.ruoyi.base.domain.vo.BaseBsZdVo;
import com.ruoyi.base.domain.vo.BdTreeVo;
import com.ruoyi.base.mapper.BaseBsFbfxMapper;
import com.ruoyi.base.mapper.BaseBsProjectMapper;
import com.ruoyi.base.mapper.BaseBsZdMapper;
import com.ruoyi.cm.domain.*;
import com.ruoyi.cm.mapper.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.ma.domain.MaMaterialSupplier;
import com.ruoyi.ma.mapper.MaMaterialSupplierMapper;
import com.ruoyi.system.domain.SysUserPower;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserPowerMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.base.domain.bo.BaseBsBdBo;
import com.ruoyi.base.domain.vo.BaseBsBdVo;
import com.ruoyi.base.mapper.BaseBsBdMapper;
import com.ruoyi.base.service.IBaseBsBdService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 标段Service业务层处理
 *
 * @author zxs
 * @date 2024-09-25
 */
@RequiredArgsConstructor
@Service
public class BaseBsBdServiceImpl implements IBaseBsBdService {

    private final BaseBsBdMapper baseMapper;
    private final BaseBsZdMapper zdMapper;
    private final MaMaterialSupplierMapper spMapper;
    private final CmBsQsMapper qsMapper;
    private final CmBsStartAdvanceMapper advanceMapper;
    private final CmBsProcessInspectionMapper inspectionMapper;
    private final CmPeriodMeasurementMapper measurementMapper;
    private final BaseBsProjectMapper projectMapper;
    private final SysDeptMapper deptMapper;
    private final SysUserPowerMapper userPowerMapper;
    private final BaseBsFbfxMapper fbfxMapper;
    private final CmBaContractSheetsMapper sheetsMapper;
    //其他计量
    private final CmBaSettleDeductDetailMapper deductDetailMapper;

//    private final ICmBsStartAdvanceService iCmBsStartAdvanceService;

    /**
     * 查询标段
     */
    @Override
    public BaseBsBdVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询标段列表
     */
    @Override
    public TableDataInfo<BaseBsBdVo> queryPageList(BaseBsBdBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseBsBd> lqw = buildQueryWrapper(bo);
        Page<BaseBsBdVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<BaseBsBdVo> records = result.getRecords();
        if(CollUtil.isNotEmpty(records)){
            //过滤关联的标段；
            Long userId = LoginHelper.getUserId();
            boolean admin = LoginHelper.isAdmin();
            if (!admin) {
                List<SysUserPower> powers = userPowerMapper.selectList(new LambdaQueryWrapper<SysUserPower>().eq(SysUserPower::getUserId, userId));
                Set<Long> powerIds = powers.stream().map(SysUserPower::getPowerId).collect(Collectors.toSet());
                List<BaseBsBdVo> collect = new ArrayList<>();
                if(CollUtil.isNotEmpty(powerIds)){
                    collect = records.stream().filter(e -> powerIds.contains(e.getId())).collect(Collectors.toList());
                }
                result.setRecords(collect);
            }
        }
        return TableDataInfo.build(result);
    }

    //标段列表不分页；
    @Override
    public R<List<BaseBsBdVo>> getList(BaseBsBdBo bo) {
        LambdaQueryWrapper<BaseBsBd> lqw = buildQueryWrapper(bo);
        List<BaseBsBdVo> baseBsBdVos = baseMapper.selectVoList(lqw);
        UserPower power = getPower();
        Set<Long> bdIds = power.getBdIds();
        baseBsBdVos = baseBsBdVos.stream().filter(e->{
            if(LoginHelper.isAdmin()|| bdIds.contains(e.getId())){
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return R.ok(baseBsBdVos);
    }


    //获取项目、标段、站点树
    @Override
    public R<List<BdTreeVo>> projectTreeList() {
        List<BaseBsProject> projectList = projectList();
        List<BdTreeVo> bdTreeVos = new ArrayList<>();
        projectList.forEach(e->{
            BdTreeVo vo = new BdTreeVo();
            vo.setId(e.getProjectId());
            vo.setLabel(e.getProjectName());
            BaseBsBdBo bo = new BaseBsBdBo();
            bo.setProjectId(e.getProjectId());
            vo.setType("xm");
            vo.setChildren(bdTreeList(bo).getData());
            bdTreeVos.add(vo);
        });
        return R.ok(bdTreeVos);
    }

    //获取标段、站点树
    @Override
    public R<List<BdTreeVo>> bdTreeList(BaseBsBdBo bo) {
        LambdaQueryWrapper<BaseBsBd> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseBsBd::getProjectId,bo.getProjectId());
        List<BaseBsBd> baseBsBds = baseMapper.selectList(wrapper);
        if(CollUtil.isEmpty(baseBsBds)){
            return R.ok(new ArrayList<>());
        }
        Set<Long> bdIds = baseBsBds.stream().map(BaseBsBd::getId).collect(Collectors.toSet());
        LambdaQueryWrapper<BaseBsZd> zdWrapper = new LambdaQueryWrapper<>();
        zdWrapper.in(BaseBsZd::getBdId,bdIds);
        List<BaseBsZd> baseBsZds = zdMapper.selectList(zdWrapper);
        return getBdTreeList(baseBsBds,baseBsZds,bo.getHasJl());
    }

    //根据项目id获取标段期数树结构；
    @Override
    public R<List<BdTreeVo>> bdQsTreeList(BaseBsBdBo bo) {
        LambdaQueryWrapper<BaseBsBd> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseBsBd::getProjectId,bo.getProjectId());
        List<BaseBsBd> baseBsBds = baseMapper.selectList(wrapper);
        if(CollUtil.isEmpty(baseBsBds)){
            return R.ok(new ArrayList<>());
        }
        Set<Long> bdIds = baseBsBds.stream().map(BaseBsBd::getId).collect(Collectors.toSet());
        LambdaQueryWrapper<CmBsQs> zdWrapper = new LambdaQueryWrapper<>();
        zdWrapper.in(CmBsQs::getBdId,bdIds);
        List<CmBsQs> qsList = qsMapper.selectList(zdWrapper);
        return getBdQsTreeList(baseBsBds,qsList);
    }

    @Override
    public R<List<BdTreeVo>> supplierTreeList(BaseBsBdBo bo) {
        LambdaQueryWrapper<BaseBsBd> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseBsBd::getProjectId,bo.getProjectId());
        List<BaseBsBd> baseBsBds = baseMapper.selectList(wrapper);
        if(CollUtil.isEmpty(baseBsBds)){
            return R.ok(new ArrayList<>());
        }

        Set<Long> bdIds = baseBsBds.stream().map(BaseBsBd::getId).collect(Collectors.toSet());
        LambdaQueryWrapper<BaseBsZd> zdWrapper = new LambdaQueryWrapper<>();
        zdWrapper.in(BaseBsZd::getBdId,bdIds);
        List<BaseBsZd> baseBsZds = zdMapper.selectList(zdWrapper);

        Set<Long> zdIds = baseBsZds.stream().map(BaseBsZd::getId).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(zdIds)) {
            LambdaQueryWrapper<MaMaterialSupplier> spWrapper = new LambdaQueryWrapper<>();
            spWrapper.in(MaMaterialSupplier::getZdId,zdIds);
            String detpId = LoginHelper.getDeptId().toString();
//            List<MaMaterialSupplier> maMaterialSuppliers = spMapper.selectList(spWrapper);
            //按当前登录用户所在物资公司过滤供应商；
            List<MaMaterialSupplier> maMaterialSuppliers = spMapper.selectList(spWrapper).stream().filter(e->LoginHelper.isAdmin()||e.getDeptId().equals(detpId)).collect(Collectors.toList());
            return getSupplierTreeList(baseBsBds, baseBsZds, maMaterialSuppliers);
        } else {
            return getBdTreeList(baseBsBds, baseBsZds,null);
        }
    }

    /**
     * 获取站点、分部分项树
     * @param bo
     * @return
     */
    @Override
    public List<BdTreeVo> getZdFbfxTreelist(BaseBsBdBo bo) {
        //查询站点下所有标段
        Long bdId = bo.getId();
        if(bdId == null){
            return new ArrayList<>();
        }
        List<BaseBsZd> zdList = zdMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId, bdId));
        if(CollUtil.isEmpty(zdList)){
            return new ArrayList<>();
        }
        Set<Long> zdIdSet = zdList.stream().map(BaseBsZd::getId).collect(Collectors.toSet());
        List<BdTreeVo> resTrees = new ArrayList<>();
        //查询站点下的所有分部分项；
        List<BaseBsFbfx> fbfxes = fbfxMapper.selectList(new LambdaQueryWrapper<BaseBsFbfx>().in(BaseBsFbfx::getZdId, zdIdSet));
        Map<Long, List<BaseBsFbfx>> fbfxMap = fbfxes.stream().collect(Collectors.groupingBy(BaseBsFbfx::getZdId));
        //遍历站点列表；
        for(BaseBsZd zd : zdList){
            List<BaseBsFbfx> fbfxes1 = fbfxMap.get(zd.getId());
            BdTreeVo treeVo = new BdTreeVo();
            treeVo.setLabel(zd.getName());
            treeVo.setType("zd");
            treeVo.setParentId(bdId);
            treeVo.setId(zd.getId());
            treeVo.setZdId(zd.getId());
            if(CollUtil.isEmpty(fbfxes1)){
                treeVo.setChildren(new ArrayList<>());
            }else{
                treeVo.setChildren(getChildren(zd.getId(),fbfxes1,zd.getId()));
            }
            resTrees.add(treeVo);
        }
        return resTrees;
    }

    /**
     * 获取标段、站点、分部分项树；
     * @param bo
     * @return
     */
    @Override
    public List<BdTreeVo> fbfxTreelist(BaseBsBdBo bo) {
        List<BdTreeVo> bdTreeVos = this.bdTreeList(bo).getData();
        if(CollUtil.isEmpty(bdTreeVos)){
            return new ArrayList<>();
        }
        //查询该标段下的所有分部分项；
        List<BaseBsFbfx> baseBsFbfxes = fbfxMapper.selectList();
        if(CollUtil.isEmpty(baseBsFbfxes)){
            return bdTreeVos;
        }
        //遍历标段List
        for(BdTreeVo bd:bdTreeVos){
            //站点列表；
            List<BdTreeVo> zdChildren = bd.getChildren();
            if(CollUtil.isEmpty(zdChildren)){
                return bdTreeVos;
            }
            //遍历站点List
            for(BdTreeVo zd : zdChildren) {
                zd.setHasGx(0);
                zd.setZdId(zd.getId());
                zd.setChildren(getChildren(zd.getId(), baseBsFbfxes, zd.getId()));
                //是否查询有无工序；标志，1查询，其他不查；
                if (bo.getHasGx() != null && bo.getHasGx() == 1) {
                    List<BaseBsFbfx> zdFbfxs = baseBsFbfxes.stream().filter(e -> zd.getZdId().equals(e.getZdId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(zdFbfxs)) {
                        Set<Long> fbfxIds = zdFbfxs.stream().map(BaseBsFbfx::getId).collect(Collectors.toSet());
                        List<CmBsProcessInspection> inspections = inspectionMapper.selectList(new LambdaQueryWrapper<CmBsProcessInspection>().
                            in(CmBsProcessInspection::getFbfxId, fbfxIds).eq(CmBsProcessInspection::getDelFlag, "0").eq(CmBsProcessInspection::getDelFlag,"0"));
                        if (CollUtil.isNotEmpty(inspections)) {
                            zd.setHasGx(1);
                        }
                    }
                }
            }
            //对站点排序，有工序的放前面；
            //排序，计量过的放在上面；
            zdChildren.sort((a, b) -> {
                if (a.getHasGx() == null) return 1; // null 排到后面
                if (b.getHasGx() == null) return -1; // null 排到后面
                return Integer.compare(b.getHasGx(), a.getHasGx()); // 降序排列，1 在前，0 在后
            });
        }
        return bdTreeVos;
    }

    @Override
    public BaseBsBdVo getInfoById(Long id) {
        BaseBsZdVo zdVo = zdMapper.selectVoById(id);
        if (zdVo == null) {
            return new BaseBsBdVo();
        }
        BaseBsBdVo bdVo = baseMapper.selectVoById(zdVo.getBdId());
        if (bdVo == null) {
            return new BaseBsBdVo();
        }
        //查询所属项目；
        BaseBsProjectVo projectVo = projectMapper.selectVoById(bdVo.getProjectId());
        bdVo.setJiansdwName(projectVo == null ? "" : projectVo.getDeptName());
        bdVo.setCapacity(BigDecimalUtil.divide(zdVo.getJiansrl(), BigDecimal.valueOf(1000), 4));
        bdVo.setZdName(zdVo.getName());
        bdVo.setAddress(zdVo.getAddress());
        return bdVo;
    }


    //递归获取子节点；
    private List<BdTreeVo> getChildren(Long id,List<BaseBsFbfx> fbfxes,Long zdId) {
        List<BdTreeVo> treeVos = new ArrayList<>();
        for (BaseBsFbfx fbfx : fbfxes) {
            BdTreeVo vo = new BdTreeVo();
            if (fbfx.getParentId() != null && fbfx.getParentId().equals(id)) {
                vo.setId(fbfx.getId());
                vo.setLabel(fbfx.getName());
                vo.setType("fbfx");
                vo.setParentId(id);
                vo.setZdId(zdId);
                vo.setChildren(getChildren(fbfx.getId(), fbfxes, zdId));
                treeVos.add(vo);
            }
        }
        return treeVos;
    }

    //生成标段期数树
    private R<List<BdTreeVo>> getBdQsTreeList(List<BaseBsBd> baseBsBds, List<CmBsQs> qsList) {
        Map<Long, List<CmBsQs>> qsMap = qsList.stream().collect(Collectors.groupingBy(CmBsQs::getBdId));
        List<BdTreeVo> bdTreeVos = new ArrayList<>();
        UserPower power = getPower();
        Set<Long> bdIds = power.getBdIds();
        baseBsBds.forEach(e->{
            if(LoginHelper.isAdmin()||bdIds.contains(e.getId())){
                BdTreeVo vo = new BdTreeVo();
                vo.setId(e.getId());
                vo.setLabel(e.getName());
                vo.setType("bd");
                //设置标段下的期数
                List<CmBsQs> qses = qsMap.get(e.getId());
                List<BdTreeVo> children = new ArrayList<>();
                if(CollUtil.isNotEmpty(qses)){
                    qses.forEach(item->{
                        BdTreeVo child = new BdTreeVo();
                        child.setId(item.getQsId());
                        child.setLabel(item.getSettleName());
                        child.setChildren(new ArrayList<>());
                        child.setParentId(e.getId());
                        child.setType("qs");
                        children.add(child);
                    });
                }
                vo.setChildren(children);
                bdTreeVos.add(vo);
            }
        });
        return R.ok(bdTreeVos);
    }

    //生成标段站点树
    private R<List<BdTreeVo>> getBdTreeList(List<BaseBsBd> baseBsBds, List<BaseBsZd> baseBsZds,Integer hasJl) {
        Map<Long, List<BaseBsZd>> zdMap = baseBsZds.stream().collect(Collectors.groupingBy(BaseBsZd::getBdId));
        List<BdTreeVo> bdTreeVos = new ArrayList<>();
        UserPower power = getPower();
        Set<Long> bdIds = power.getBdIds();
        Set<Long> zdIds = power.getZdIds();
        baseBsBds.forEach(e->{
            if(LoginHelper.isAdmin() || bdIds.contains(e.getId())){
                BdTreeVo vo = new BdTreeVo();
                vo.setId(e.getId());
                vo.setLabel(e.getName());
                vo.setType("bd");
                //设置标段下的站点
                List<BaseBsZd> zdList = zdMap.get(e.getId());
                List<BdTreeVo> children = new ArrayList<>();
                if(CollUtil.isNotEmpty(zdList)){
                    List<CmBsQs> qsList = qsMapper.selectList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId,e.getId()));
                    Set<Long> qsIds = qsList.stream().map(CmBsQs::getQsId).collect(Collectors.toSet());
                    zdList.forEach(item->{
                        if(LoginHelper.isAdmin()|| zdIds.contains(item.getId())) {
                            BdTreeVo child = new BdTreeVo();
                            child.setId(item.getId());
                            child.setLabel(item.getName());
                            child.setChildren(new ArrayList<>());
                            child.setParentId(e.getId());
                            child.setType("zd");
                            if (hasJl != null ) {
                                if (hasJl == 1) {
                                    child.setJlg(getJlStatus(item.getId()));
                                } else if (hasJl == 2) {
                                    child.setJlg(getJlStatusHtqd(item.getId()));
                                } else if (hasJl == 3){
                                    child.setJlg(getJlStatusQtjl(item.getId()));
                                }
                            }
                            children.add(child);
                        }
                    });
                }
                //排序，计量过的放在上面；
                children.sort((a, b) -> {
                    if (a.getJlg() == null) return 1; // null 排到后面
                    if (b.getJlg() == null) return -1; // null 排到后面
                    return Integer.compare(b.getJlg(), a.getJlg()); // 降序排列，1 在前，0 在后
                });
                vo.setChildren(children);
                bdTreeVos.add(vo);
            }
        });
        return R.ok(bdTreeVos);
    }

    /**
     * 各站点其他计量是否计量过；
     * @param id
     * @return 1, 计量过
     *         0，未计量；
     */
    private Integer getJlStatusQtjl(Long id) {
        List<CmBaSettleDeductDetail> deductDetails = deductDetailMapper.selectList(new LambdaQueryWrapper<CmBaSettleDeductDetail>().eq(CmBaSettleDeductDetail::getZdId,id));
        if(CollUtil.isNotEmpty(deductDetails)){
            return 1;
        }
        return 0;
    }

    /**
     * 查询各站点合同清单是否有数据
     * @param id
     * @return 1,有数据
     *         0，没数据；
     */
    private Integer getJlStatusHtqd(Long id) {
        List<CmBaContractSheets> sheets = sheetsMapper.selectList(new LambdaQueryWrapper<CmBaContractSheets>().eq(CmBaContractSheets::getZdId,id));
        if(CollUtil.isNotEmpty(sheets)){
            return 1;
        }
        return 0;
    }

    /**
     * 查询当前站点是否已计量；
     * 1.没有计量数据；
     * 2.没有开工预付款；
     *
     * return 1,计量过；0，未计量
     */
    private Integer getJlStatus(Long id) {
        //开工预付款
//        CmBsStartAdvanceBo bo = new CmBsStartAdvanceBo();
//        bo.setZdId(id);
//        bo.setBdId(bdId);
//        ICmBsStartAdvanceService iCmBsStartAdvanceService = SpringUtils.getBean(ICmBsStartAdvanceService.class);
//        List<CmBsStartAdvanceVo> advanceVos = iCmBsStartAdvanceService.listData(bo);
//        advanceVos = advanceVos.stream().filter(e->e.getZdId().equals(id) && qsIds.contains(e.getQsId())).collect(Collectors.toList());
//        if(CollUtil.isNotEmpty(advanceVos)){
//            return 1;
//        }
        //中间计量
        List<CmPeriodMeasurement> measurements = measurementMapper.selectList(new LambdaQueryWrapper<CmPeriodMeasurement>().eq(CmPeriodMeasurement::getZdId,id));
        if(CollUtil.isEmpty(measurements)){
            return 0;
        }
        for(CmPeriodMeasurement measurement : measurements){
            BigDecimal mea = measurement.getMeasurementQuantity();
            if(mea!=null && mea.compareTo(BigDecimal.ZERO)!=0){
                return 1;
            }
        }
        return 0;
    }

    //生成标段站点树
    private R<List<BdTreeVo>> getSupplierTreeList(List<BaseBsBd> baseBsBds, List<BaseBsZd> baseBsZds, List<MaMaterialSupplier> maMaterialSuppliers) {
        R<List<BdTreeVo>> bdTree = getBdTreeList(baseBsBds, baseBsZds,null);
        List<BdTreeVo> list = bdTree.getData();
        Map<Long, List<MaMaterialSupplier>> spMap = maMaterialSuppliers.stream().collect(Collectors.groupingBy(MaMaterialSupplier::getZdId));
        list.forEach(e -> {
            // 设置站点下供应商信息
            if (CollUtil.isNotEmpty(e.getChildren())) {
                List<BdTreeVo> vos = e.getChildren();
                if (CollUtil.isNotEmpty(vos)) {
                    vos.forEach(vo -> {
                        List<MaMaterialSupplier> spList = spMap.get(vo.getId());
                        List<BdTreeVo> children = new ArrayList<>();
                        if(CollUtil.isNotEmpty(spList)){
                            spList.forEach(item->{
                                BdTreeVo child = new BdTreeVo();
                                child.setId(item.getSupplierId());
                                child.setLabel(item.getDeptName()+"("+(StringUtils.isNotBlank(item.getGhcl())?item.getGhcl():"")+")");
                                child.setValue(item.getGhclDictValue());
                                child.setChildren(new ArrayList<>());
                                child.setParentId(vo.getId());
                                child.setType("supplier");
                                children.add(child);
                            });
                        }
                        vo.setChildren(children);
                    });
                }
            }
        });
        return R.ok(list);
    }

    /**
     * 查询标段列表
     */
    @Override
    public List<BaseBsBdVo> queryList(BaseBsBdBo bo) {
        LambdaQueryWrapper<BaseBsBd> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BaseBsBd> buildQueryWrapper(BaseBsBdBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseBsBd> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getProjectId() != null, BaseBsBd::getProjectId, bo.getProjectId());
        lqw.eq(bo.getParentId() != null, BaseBsBd::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), BaseBsBd::getName, bo.getName());
        lqw.eq(bo.getSort() != null, BaseBsBd::getSort, bo.getSort());
        lqw.eq(bo.getSgdwId() != null, BaseBsBd::getSgdwId, bo.getSgdwId());
        lqw.like(StringUtils.isNotBlank(bo.getSgdwName()), BaseBsBd::getSgdwName, bo.getSgdwName());
        lqw.eq(bo.getJldwId() != null, BaseBsBd::getJldwId, bo.getJldwId());
        lqw.like(StringUtils.isNotBlank(bo.getJldwName()), BaseBsBd::getJldwName, bo.getJldwName());
        lqw.eq(bo.getSjdwId() != null, BaseBsBd::getSjdwId, bo.getSjdwId());
        lqw.like(StringUtils.isNotBlank(bo.getSjdwName()), BaseBsBd::getSjdwName, bo.getSjdwName());
        lqw.eq(bo.getShejdwId() != null, BaseBsBd::getShejdwId, bo.getShejdwId());
        lqw.like(StringUtils.isNotBlank(bo.getShejdwName()), BaseBsBd::getShejdwName, bo.getShejdwName());
        return lqw;
    }

    /**
     * 新增标段
     */
    @Override
    public Boolean insertByBo(BaseBsBdBo bo) {
        BaseBsBd add = BeanUtil.toBean(bo, BaseBsBd.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            //加权限；
            List<SysUserPower> powers = userPowerMapper.selectList(new LambdaQueryWrapper<SysUserPower>().eq(SysUserPower::getPowerId, bo.getProjectId()));
            if(CollUtil.isNotEmpty(powers)){
                powers.forEach(e->{
                    e.setPowerId(add.getId());
                    e.setId(null);
                });
            }
            userPowerMapper.insertBatch(powers);
        }
        return flag;
    }

    /**
     * 修改标段
     */
    @Override
    public Boolean updateByBo(BaseBsBdBo bo) {
        BaseBsBd update = BeanUtil.toBean(bo, BaseBsBd.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseBsBd entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除标段
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    //当前登录人所属单位（包括子单位）下的所有项目列表  并按关联项目过滤；
    @Override
    public List<BaseBsProject> projectList() {
        Long deptId = LoginHelper.getDeptId();
        String username = LoginHelper.getUsername();
        LambdaQueryWrapper<SysDept> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.equals("admin",username)){
            lambdaQueryWrapper.eq(SysDept::getDeptId, deptId);
            lambdaQueryWrapper.last("or ancestors like '%" + deptId + "%'");
        }
        List<SysDept> sysDepts = deptMapper.selectList(lambdaQueryWrapper);
        List<BaseBsProject> projectList = projectMapper.selectList();
        if (CollUtil.isNotEmpty(sysDepts)) {
            Map<Long, String> deptNames = new HashMap<>();
            sysDepts.forEach(e -> deptNames.put(e.getDeptId(), e.getDeptNameShort()));
            projectList.forEach(e -> e.setDeptNameShort(deptNames.get(e.getDeptId())));
        }
        if(LoginHelper.isAdmin()){
            return projectList;
        }
        //查询当前用户勾选的关联项目；
        Set<Long> projectIds = getPower().getAllProjectIds();
        //如果当前用户没有关联项目，返回空列表；
        if(CollUtil.isEmpty(projectIds)){
            return new ArrayList<>();
        }
        Set<Long> finalProjectIds = projectIds;
        projectList = projectList.stream().filter(e -> finalProjectIds.contains(e.getProjectId())).collect(Collectors.toList());
        return projectList;
    }


    //获取用户的关联项目、关联标段、关联站点id集合；
    public UserPower getPower(){
        Long userId = LoginHelper.getUserId();
        List<SysUserPower> powers = userPowerMapper.selectList(new LambdaQueryWrapper<SysUserPower>().eq(SysUserPower::getUserId,userId));
        Set<Long> zd = powers.stream().map(SysUserPower::getPowerId).collect(Collectors.toSet());
        UserPower power = new UserPower();
        if(CollUtil.isNotEmpty(zd)){
            //根据用户关联项目id查询站点
            List<BaseBsZdVo> baseBsZdVos = zdMapper.selectVoBatchIds(zd);
            //用户勾选的站点id；
            Set<Long> zdIdSet = baseBsZdVos.stream().map(BaseBsZdVo::getId).collect(Collectors.toSet());
            power.setZdIds(zdIdSet);
            //根据用户关联项目id查询标段；
            List<BaseBsBdVo> bdVos = baseMapper.selectVoBatchIds(zd);
            //用户勾选的标段id；
            Set<Long> bdIdSet = bdVos.stream().map(BaseBsBdVo::getId).collect(Collectors.toSet());
            power.setBdIds(bdIdSet);

            Set<Long> zdIds = new HashSet<>();
            Set<Long> bdIds = new HashSet<>();
            Set<Long> proIds = new HashSet<>();
            Set<Long> projectIds = new HashSet<>();
            //区分项目id，标段id，站点id；
            for(Long pId : zd) {
                if (zdIdSet.contains(pId)) {
                    zdIds.add(pId);
                } else if (bdIdSet.contains(pId)) {
                    bdIds.add(pId);
                } else {
                    proIds.add(pId);
                }
            }
            //用户勾选的项目id
            power.setProjectIds(proIds);
            Set<Long> bdIdset= baseBsZdVos.stream().map(BaseBsZdVo::getBdId).collect(Collectors.toSet());
            bdIds.addAll(bdIdset);
            if(CollUtil.isNotEmpty(bdIds)){
                List<BaseBsBdVo> baseBsBdVos = baseMapper.selectVoBatchIds(bdIds);
                projectIds = baseBsBdVos.stream().map(BaseBsBdVo::getProjectId).collect(Collectors.toSet());
            }
            projectIds.addAll(proIds);
            //所有的关联项目id；
            power.setAllProjectIds(projectIds);
        }
        return power;
    }

}
